<template>
  <div class="dashboard-container">
    <div class="dashboard-text">
      <el-card class="box-card">
        <!-- 头部功能块 -->
        <el-row slot="header" class="clearfix" type="flex" justify="space-between">
          <!-- 添加客户按钮 -->
          <span style="margin-right:520px">
            <el-button type="primary" @click="showDialog = true">添加客户</el-button>
          </span>
          <div>
            <el-row type="flex" justify="end">
              <!-- 下拉框 -->
              <!-- <el-dropdown>
                <el-button type="primary" class="KHbtn" style="height:40px">
                  全部经纪<i class="el-icon-arrow-down el-icon--right" />
                </el-button>
                <el-dropdown-menu v-for="item in brokerData" :key="item.id" slot="dropdown">
                  <el-dropdown-item>{{ item.name }}</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown> -->
              <el-select v-model="agent" placeholder="全部经纪" style="margin-right:5px">
                <el-option value="" label="全部经纪" />
                <el-option
                  v-for="item in brokerData"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
              <!-- 搜索框 -->
              <el-input v-model="searchData.name_contains" placeholder="请输入关键字" style="width:400px" />
              <!-- 筛选按钮 -->
              <el-button style="height:40px" @click="screen">筛选</el-button>
            </el-row>
          </div>
        </el-row>
        <!-- 内容表格 -->
        <el-table
          :data="tableData"
          style="width: 100%"
          border
        >
          <el-table-column
            prop="image"
            label="图片"
          >
            <template #default="{row}">
              <img :src="row.image" alt="" style="height:100px">
            </template>
          </el-table-column>
          <el-table-column
            prop="name"
            label="名称"
          />
          <el-table-column
            prop="email"
            label="邮箱"
          />
          <el-table-column
            prop="phone"
            label="电话"
          />
          <el-table-column
            prop="agent"
            label="经纪"
          >
            <template #default="{row}">
              <span>{{ row.agent&&row.agent.name }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="wechat"
            label="微信"
          />
          <el-table-column
            prop="desc"
            label="介绍"
          />
          <el-table-column
            label="操作"
          >
            <template #default="{row}">
              <el-button type="primary" class="btncolor" @click="ediClient(row.id)">编辑</el-button>
              <el-button type="danger" class="btncolor" @click="delClient(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页功能 -->
        <el-row type="flex" align="middle" justify="center" style="height:60px">
          <el-pagination
            layout="prev, pager, next,total"
            :page-size="page.pageSize"
            :total="total"
            :current-page="page.pageIndex"
            @current-change="changePage"
          />
        </el-row>
      </el-card>
    </div>

    <!-- 弹出框 -->
    <el-dialog :title="form.id?'编辑客户':'新增客户'" :visible="showDialog" :destroy-on-close="true" @close="btnCancel">
      <!-- 表单 -->
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" size="30px" label-position="top">
        <el-form-item label="经纪" prop="agent">
          <el-select v-model="form.agent" placeholder="Select">
            <el-option
              v-for="item in brokerData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="微信" prop="wechat">
          <el-input v-model="form.wechat" />
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input
            v-model="form.desc"
            type="textarea"
            :rows="3"
            placeholder="请输入内容"
            resize="none"
          />
        </el-form-item>
        <el-form-item label="封面" prop="image">
          <ImageUpload ref="userInfoPhoto" />
        </el-form-item>
      </el-form>
      <!-- footer插槽 -->
      <template v-slot:footer>
        <el-row type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="btnCancel">取消</el-button>
            <el-button type="primary" size="small" @click.stop="btnOk">确定</el-button>
          </el-col>
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getuserInfo, getAgents, delClients, addClients, getUpClients, updataClients, clientsCount } from '@/api/client'
import ImageUpload from '@/components/ImageUpload'
export default {
  components: { ImageUpload },
  data() {
    return {
      // 分页
      page: {
        pageIndex: 1,
        pageSize: 2
      },
      total: 0,

      imageUrl: '', // 封面
      showDialog: false, // 新增弹出框
      // searchvla: '', // 搜索框输入的值
      searchData: { // 模糊搜索传的参
        _limit: 2,
        _start: 0,
        name_contains: ''
      },
      tableData: [], // 表格数据
      brokerData: [], // 获取经纪
      email: [], // 邮箱
      agent: '',
      form: {
        agent: '', // 经济
        name: '', // 名称
        email: '', // 邮箱
        phone: '', // 电话
        wechat: '', // 微信
        desc: '', // 描述
        image: ''// 图片
      },
      userId: this.$store.getters.userId,
      value: '',
      value1: '',
      // 校验表单
      rules: {
        name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 2, max: 4, message: '长度在 2 到 4 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不对', trigger: 'blur' }
        ],
        wechat: [
          { required: true, message: '请输入微信号', trigger: 'blur' }
        ],
        describe: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 5, max: 30, message: '长度在 5 到 30 个字符', trigger: 'blur' }
        ],
        agent: [
          { required: true, message: '请选择经纪', trigger: 'change' }
        ]
      }

    }
  },
  created() {
    this.getuserInfo()
    this.getAgents()
    this.clientsCount()
  },
  methods: {
    // 实现翻页
    changePage(newPage) {
      this.page.pageIndex = newPage
      console.log(newPage)
      // this.searchData.agent_contains = this.form.agent
      this.searchData._start = Number((newPage - 1) * this.searchData._limit)
      // if (this.searchData.name_contains !== '' || (this.form.agent && this.form.agent !== '全部经纪')) {
      //   this.searchData.agent_contains = this.form.agent
      // }
      //  else if (this.form.agent === '全部经纪' && this.searchData.name_contains !== '') {
      //   this.searchData.agent_contains = ''
      // }
      // console.log(2)
      // console.log(229, this.form.agent)
      this.getuserInfo()
    },

    // 获取分页数量
    async clientsCount() {
      if (this.agent === '' && this.searchData.name_contains === '') {
        const { data } = await clientsCount(this.searchData)
        this.total = data
      } else {
        const { data } = await clientsCount({ ...this.searchData, agent_contains: this.agent })
        this.total = data
      }

      // this.getuserInfo()
    },

    // 编辑客户功能
    async ediClient(id) {
      // console.log(210, id)
      const { data } = await getUpClients(id)
      console.log('编辑', data)
      this.form = { ...data, agent: data.agent === null ? '' : data.agent.name }
      // this.brokerData.id = data.agent.id
      this.showDialog = true
      // 回显图片
      console.log(264, this.form.image)
      if (this.form.image) {
        this.$nextTick(() => {
          this.$refs.userInfoPhoto.fileList = [{
            url: this.form.image
          }]
        })
      }
    },

    // 删除客户功能
    async delClient(id) {
      // 二次询问是否删除
      await this.$confirm('是否确定删除客户')
      // 发起请求
      await delClients(id)
      // 提示用户
      this.$message.success('删除成功')
      // 刷新页面
      if (this.tableData.length === 1 && this.page.pageIndex > 1) {
        this.page.pageIndex--
        this.searchData._start = Number((this.page.pageIndex - 1) * this.searchData._limit)
      }
      const res = await clientsCount(this.searchData)
      this.total = res.data
      console.log(this.total)
      const { data } = await getuserInfo(this.searchData)
      this.tableData = data
    },

    // 获取客户数据
    async getuserInfo() {
      if (this.agent === '') {
        const { data } = await getuserInfo(this.searchData)
        this.tableData = data
      } else {
        const { data } = await getuserInfo({ ...this.searchData, agent_contains: this.agent })
        this.tableData = data
      }

      // console.log('客户数据', this.tableData)
    },

    // 获取经纪
    async getAgents() {
      const { data } = await getAgents()
      this.brokerData = data
      console.log(284, data)
    },

    // 点击筛选进行模糊搜索
    async screen() {
      // this.searchData.agent_contains = ''
      this.page.pageIndex = 1
      this.searchData._start = Number((this.page.pageIndex - 1) * this.searchData._limit)
      console.log(300, this.searchData)
      console.log(30, this.agent)

      // if ((this.searchData.name_contains !== '' && !this.form.agent) || (this.searchData.name_contains !== '' && this.form.agent === '全部经纪')) {
      //   console.log(11)
      //   const { data } = await getuserInfo({ ...this.searchData, name_contains: this.searchData.name_contains, agent_contains: '' })
      //   this.tableData = data
      //   const res = await clientsCount({ ...this.searchData, name_contains: this.searchData.name_contains, _start: 0 })
      //   this.total = res.data
      //   this.clientsCount()
      // } else if ((this.searchData.name_contains === '' && (this.form.agent && this.form.agent !== '全部经纪')) || (this.searchData.name_contains !== '' && this.form.agent)) {
      //   console.log(2)
      //   const { data } = await getuserInfo({ ...this.searchData, name_contains: this.searchData.name_contains, agent: this.form.agent, _start: 0 })
      //   this.tableData = data
      //   const res = await clientsCount({ ...this.searchData, agent: this.form.agent, name_contains: this.searchData.name_contains, _start: 0 })
      //   this.total = res.data
      // } else if (this.searchData.name_contains === '' && this.form.agent === '全部经纪') {
      //   console.log(3)
      //   const { data } = await getuserInfo({ ...this.searchData, name_contains: '', _start: 0 })
      //   this.tableData = data
      //   const res = await clientsCount({ ...this.searchData, name_contains: this.searchData.name_contains, _start: 0 })
      //   this.total = res.data
      // } else {
      //   console.log(4)
      //   this.getuserInfo()
      //   this.clientsCount()
      // }
      // 1.全部经济，输入框为空 =》搜索全部
      if (this.agent === '' && this.searchData.name_contains === '') {
        const { data } = await getuserInfo(this.searchData)
        console.log(335, data)
        this.tableData = data
        const res = await clientsCount(this.searchData)
        console.log(344, res)
        this.total = res.data
      }
      // 2.有经济，输入框为空 =》根据经纪搜索
      if (this.agent !== '' && this.searchData.name_contains === '') {
        const { data } = await getuserInfo({ ...this.searchData, agent_contains: this.agent })
        console.log(343, data)
        this.tableData = data
        const res = await clientsCount({ ...this.searchData, agent_contains: this.agent })
        console.log(344, res)
        this.total = res.data
        // this.clientsCount()
      }
      // 3.全部经纪，输入框不为空=》根据输入框搜索
      if (this.agent === '' && this.searchData.name_contains !== '') {
        const { data } = await getuserInfo({ ...this.searchData, agent_contains: this.agent })
        console.log(360, data)
        this.tableData = data
        const res = await clientsCount({ ...this.searchData, agent_contains: this.agent })
        console.log(363, res)
        this.total = res.data
      }
      // 4.有经济，输入框不为空，=》准确搜索
      if (this.agent !== '' && this.searchData.name_contains !== '') {
        const { data } = await getuserInfo({ ...this.searchData, agent_contains: this.agent })
        console.log(360, data)
        this.tableData = data
        const res = await clientsCount({ ...this.searchData, agent_contains: this.agent })
        console.log(363, res)
        this.total = res.data
      }
    },

    // 弹框的取消按钮
    btnCancel() {
      // 清空表单校验
      this.$refs.form.resetFields()
      //
      this.$refs.userInfoPhoto.fileList = []
      // 清空数据
      this.form = {
        agent: '',
        name: '', // 姓名
        email: '', // 邮箱
        phone: '', // 电话
        wechat: '', // 微信
        describe: '', // 描述
        image: '', // 图片
        id: ''
      }

      // 关闭弹窗
      this.showDialog = false
    },
    // 弹框的确定按钮
    async btnOk() {
      try {
        // 校验表单
        await this.$refs.form.validate()
        // 封装组件里的所有数据
        const fileList = this.$refs.userInfoPhoto.fileList
        if (this.form.id) {
        // 发起编辑请求
          await updataClients({ ...this.form, image: fileList[0] ? fileList[0].url : '' })
          // 提示用户
          this.$message.success('编辑客户成功')
          // console.log(357, this.pageIndex)
          // this.searchData._start = Number((this.pageIndex - 1) * this.searchData._limit)
        } else {
        // 发送新增请求
          await addClients({ ...this.form, image: fileList[0] ? fileList[0].url : '' })
          // 提示用户
          this.$message.success('添加客户成功')
        // this.clientsCount()
        }
        // 清空表单数据
        this.$refs.form.resetFields()
        // 关闭弹窗
        this.showDialog = false
        // 更新页面
        this.getuserInfo()
        this.clientsCount()
      } catch (err) {
        console.log(err)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
  }
  &-text {
    // font-size: 30px;
    line-height: 46px;
  }
}
.KHbtn{
    color: #777;
    border-color: #ccc;
    background-color: #fff;
}
.base{
    display: flex;
    justify-content: center;
    margin: 20px;
    height: 10px;
}
.btncolor{
    font-size: 12px;
    padding: 7px 15px;
}
</style>
